package com.mediacloud.app.newsmodule.fragment;

import java.util.List;
import java.util.Map;

import com.mediacloud.app.fbnavsk.SecondFloorHandlerKt;
import com.mediacloud.app.fbnavsk.SecondNav;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.nav2.fragment.HqyNavFragment;
import com.mediacloud.app.newsmodule.fragment.video.vod.PlayClickListener;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoListPlayerUtil;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.view.XSmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.views.XRefreashExpandableListView.IXListViewListener;
import com.mediacloud.app.cloud.ijkplayersdk.video.MultiUtils;
import com.mediacloud.app.cloud.ijkplayersdk.video.MultiVideoMannager;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.LBSChooseListener;
import com.mediacloud.app.newsmodule.view.ComponentContainer;
import com.mediacloud.app.model.adaptor.BaseExpandableListAdapterX;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.newsmodule.view.LocationChooseHeader;
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import static com.mediacloud.app.nav2.fragment.HqyNavFragmentKt.FLAG_SCROLL_POSITION;
import static com.mediacloud.app.nav2.fragment.HqyNavFragmentKt.FLAG_SCROLL_TOP;

/**
 * 带分组的下拉刷新列表
 * @author x
 *
 * @param <T> adaptor泛型
 * @param <Parent> 分组列表
 * @param <Child>  分组列表项下对应的子列表
 * @param <K>
 * @param <E>
 */
public abstract class BaseExpandListFragment<T extends BaseExpandableListAdapterX<Parent, Child, K, E>, Parent extends List<K>, Child extends Map<K, List<E>>, K, E> extends HqyNavFragment
        implements IXListViewListener, OnRefreshLoadMoreListener, ToolBarActionF5OrTop, PlayClickListener {

    /**
     * 上一次滚动停留的位置
     */
    protected int lastSelectedPosition;
    /**
     * 上一次滚动位置的偏差
     */
    protected int lastSelectedPositionOffset = 0;
    /**
     * 以这个作为一瓶显示数据的标记位，超过这个值就认为滚过了一屏
     */
    private int visibleItemCount = -1;


    protected T adaptor;
    public ExpandableListView mCatalogContentItemListView;
    protected XSmartRefreshLayout refreshLayout;
    public View mEmptyContent;
    protected TextView emptyTipsText;
    protected boolean isLoading = false;
    protected boolean attached = false;
    protected final String SaveAdaptor = "SaveAdaptor";
    protected final String SaveArgs = "SaveArgs";
    protected LinearLayout headerViewContainer;
    protected int pageNum = 1;
    //点直播 专辑默认取所有 为0
    protected final int pageSize = 20;
    /**
     * 组件的
     */
    protected ComponentContainer componetContainer;
    protected Child childGropData;
    protected Parent groupLabel;

    public BaseExpandListFragment() {
    }

    @Override
    public int getLayoutResID() {
        return R.layout.fragment_expandlist_newslist;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        headerViewContainer = new LinearLayout(getActivity());
        headerViewContainer.setOrientation(LinearLayout.VERTICAL);
        componetContainer = new ComponentContainer(getActivity(),getCurrentICMP26Holder());
        componetContainer.setPlayClickListener(this);
        headerViewContainer.addView(componetContainer);
    }

    @CallSuper
    @Override
    protected void initOther() {
        super.initOther();
        componetContainer.setmListView(this.mCatalogContentItemListView);
        componetContainer.setRootView(mRootView);
        mCatalogContentItemListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (visibleItemCount == -1) {
                    return;
                }
                if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                    if (view.getFirstVisiblePosition() >= visibleItemCount && !hasScrollerFlag(FLAG_SCROLL_POSITION)) {
                        setScrollerFlag(FLAG_SCROLL_POSITION);
                    } else if (view.getFirstVisiblePosition() < visibleItemCount && !hasScrollerFlag(FLAG_SCROLL_TOP)) {
                        setScrollerFlag(FLAG_SCROLL_TOP);
                    }
                }
                //判断ListView是否滑动到第一个Item的顶部
                if (refreshLayout!=null&&mCatalogContentItemListView.getChildCount() > 0 && mCatalogContentItemListView.getFirstVisiblePosition() == 0
                        && mCatalogContentItemListView.getChildAt(0).getTop() >= mCatalogContentItemListView.getPaddingTop()) {
                    //解决滑动冲突，当滑动到第一个item，下拉刷新才起作用
                    refreshLayout.setEnableRefresh(true);
                } else {
                    refreshLayout.setEnableRefresh(false);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (BaseExpandListFragment.this.visibleItemCount == -1 || BaseExpandListFragment.this.visibleItemCount == 0) {
                    BaseExpandListFragment.this.visibleItemCount = visibleItemCount;
                }
            }
        });
    }

    @CallSuper
    public void doRefresh() {
        if (componetContainer != null) {
            componetContainer.stopWindows();
            componetContainer.stopUpSmallVideoUi();
        }
    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
        if (childGropData != null)
            childGropData.clear();
        if (groupLabel != null)
            groupLabel.clear();
        if (mVideoListPlayerUtil != null)
            mVideoListPlayerUtil.onDestroy();
        if (componetContainer!=null) {
            componetContainer.dispose();
        }
        super.onDestroy();
    }

    @Override
    public final void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        onLoadMore();
    }

    @Override
    public final void onRefresh(@NonNull RefreshLayout refreshLayout) {
        onRefresh();
    }


    public abstract class BaseDataInvokeCallBack<CallBack> implements DataInvokeCallBack<CallBack> {
        @Override
        public void fault(Object object) {
            isLoading = false;
            pageNum--;
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            if (adaptor != null && (adaptor.getBaseExpandableLisChilds() == null
                    || adaptor.getBaseExpandableLisChilds().size() == 0)) {
                if (object == null) {
                    showStateView(TYPE_NO_CONTENT, false);
                } else {
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
                }
            } else {
                closeStateView();
            }
        }
    }

    protected final void addLBSChosoeHeader(CatalogItem catalogItem) {
        //LBS栏目不为空就加上头
        if (catalogItem != null && catalogItem.getLbsItem() != null) {
            int maxLBSH = getActivity().getResources().getDimensionPixelSize(R.dimen.dime_fifty);
            LocationChooseHeader locationChooseHeader = new LocationChooseHeader(getActivity());
            locationChooseHeader.catalogItem = catalogItem;
            locationChooseHeader.tag = FGTag.TagID;
            locationChooseHeader.setVisiableHeight(maxLBSH);
            mCatalogContentItemListView.addHeaderView(locationChooseHeader);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LBSChooseListener.Request && resultCode == Activity.RESULT_OK)
            LBSChooseListener.getInstance().onActivityResult(data, this);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        registerMulti();
    }


    @Override
    public void onPause() {

        super.onPause();
        if (componetContainer != null && componetContainer.mMultiVideoPlayer != null) {

            if (MultiVideoMannager.getInstace().isHandPause) {
            } else {
                componetContainer.mMultiVideoPlayer.onPause();
            }
        }
    }

    @Override
    public void onResume() {
        if (componetContainer != null && componetContainer.mMultiVideoPlayer != null) {
            if (MultiVideoMannager.getInstace().isHandPause) {

            } else {
                componetContainer.mMultiVideoPlayer.onStart();
            }
        }
        if (emptyTipsText == null) {
            emptyTipsText = Utility.findViewById(mRootView, R.id.emptyTipsText);
        }
        super.onResume();
    }

    public abstract void useCache();
    private void registerMulti() {

        IntentFilter filter = new IntentFilter();
        filter.addAction(MultiUtils.outFullbord);
        filter.addAction(MultiUtils.closeThe);

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, filter);
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            //Log.i("test", "mReceiver action:" + action);
            if (action != null) {
                if (componetContainer != null && componetContainer.mMultiVideoPlayer != null) {

                    if (action.equals(MultiUtils.outFullbord)) {
                        componetContainer.mMultiVideoPlayer.outFullScreen();
                    } else if (action.equals(MultiUtils.closeThe)) {
                        stopThePlayer();
                        isExcode = false;
                    }
                }


            }


        }
    };


    @CallSuper
    @Override
    public void unChosoed() {
        super.unChosoed();
        stopThePlayer();
    }

    boolean isVisible = false;
    boolean isExcode = false;

    private void stopThePlayer() {
        if (componetContainer != null && !isExcode) {
            componetContainer.stopWindows();
            //componetContainer.mMultiVideoPlayer.stopPlay();
            componetContainer.stopUpSmallVideoUi();
            isExcode = true;
        }
        MultiVideoMannager.getInstace().isHiden = true;

    }

    @CallSuper
    @Override
    public void choosed() {
        super.choosed();
        isExcode = false;
    }

    @CallSuper
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);
        //Log.i("test", "player:setUserVisibleHint");
        if (getUserVisibleHint()) {
            isVisible = true;
            //   isExcode=false;
            //Log.i("test", "player:hiden?:visible");
        } else {

            //Log.i("test", "player:hiden?:GONE");
            if (mVideoListPlayerUtil != null) {
                mVideoListPlayerUtil.stopPlay();
            }
            // isVisible = false;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //Log.i("test", "player:onHiddenChanged:" + hidden);
        if (hidden) {

            if (componetContainer != null) {
                componetContainer.stopWindows();
                componetContainer.stopUpSmallVideoUi();
            }
            MultiVideoMannager.getInstace().isHiden = true;
        } else {

        }
    }


    @CallSuper
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        super.onViewCreated(view, savedInstanceState);
        SecondFloorHandlerKt.navPaddingTopMatch(this);
      //  useCache();
    }

    @Override
    public void initView() {
        if (getFragmentArguments() != null) {
            saveInstanceArguments = getFragmentArguments();
            catalogID = saveInstanceArguments.getString("id");
            catalogItem = saveInstanceArguments.getParcelable("catalog");
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments.getString("id");
            catalogItem = saveInstanceArguments.getParcelable("catalog");
        }
    }

    @Override
    public final void f5() {
        mCatalogContentItemListView.setSelection(0);
        refreshLayout.autoRefresh(200);
    }

    @Override
    public final void gun() {
        //这里也会滚动到顶部，处理一下滚动状态
        setScrollParams();
        setScrollerFlag(FLAG_SCROLL_TOP);
        mCatalogContentItemListView.setSelection(0);
    }

    @Override
    public boolean handleScroller() {
        if (hasScrollerFlag(FLAG_SCROLL_TOP)) {
            setScrollerFlag(FLAG_SCROLL_POSITION);
            mCatalogContentItemListView.setSelectionFromTop(lastSelectedPosition, lastSelectedPositionOffset);
            return true;
        }
        if (hasScrollerFlag(FLAG_SCROLL_POSITION)) {
            setScrollParams();
            setScrollerFlag(FLAG_SCROLL_TOP);
            refreshLayout.getRefreshKernel().moveSpinner(0, false);
            mCatalogContentItemListView.requestFocusFromTouch();
            mCatalogContentItemListView.setSelection(0);
            return true;
        }
        return true;
    }

    private void setScrollParams() {
        lastSelectedPosition = mCatalogContentItemListView.getFirstVisiblePosition();
        View view = mCatalogContentItemListView.getChildAt(0);
        if (view != null) {
            lastSelectedPositionOffset = view.getTop();
        }
    }

    public VideoListPlayerUtil mVideoListPlayerUtil;
    protected String catalogID;
    protected CatalogItem catalogItem;

    @Override
    public void onPlayIcoClick(View rootView, ViewGroup container, View playIcon,final ArticleItem item) {
        if (mVideoListPlayerUtil == null) {
            mVideoListPlayerUtil = new VideoListPlayerUtil(getActivity(), mCatalogContentItemListView,this);
            mVideoListPlayerUtil.setHqyNavFragment(this);
            if(getParentFragment() instanceof SecondNav){
                mVideoListPlayerUtil.mPlayer.setViewPlayer(((SecondNav)getParentFragment() ).getViewPager());
            }
        }

        if (item!=null&&mVideoListPlayerUtil.item!=null&&mVideoListPlayerUtil.getPlayer()!=null
                &&mVideoListPlayerUtil.item.equals(item)&&mVideoListPlayerUtil.getPlayer().isPlaying()){
            return;
        }
        mVideoListPlayerUtil.setPlayerContainer(rootView, container, playIcon,!TextUtils.isEmpty(item.getGoodsID()), v -> {
            item.setParentId(catalogID);
            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, catalogItem);
        }, item);
        mVideoListPlayerUtil.setVideoDetail(catalogID + "", item);
    }
}